import React, { Component } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import {
  Form,
  Input,
  DatePicker,
  Select,
  Button,
  Card,
  InputNumber,
  Radio,
  Row,
  Col,
  message,
  Modal,
  Text,
  Icon,
  TimePicker,
} from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
//import TimePickerRange from '../../components/TimePickerRange';
import SelectCutIn from '../../components/UpLoadForm/SelectCutIn';
import Styles from './BasicList.less';
import { Label } from 'rc-bmap';
import { isArray } from 'lodash';

let id = 1;
const FormItem = Form.Item;
const { Option } = Select;
const { RangePicker } = DatePicker;

@connect(({ cutinlib, dev, loading }) => ({
  cutinlib,
  dev,
  submitting: loading.effects['program/addcutintask'],
}))
@Form.create()
export default class AddCutInTask extends Component {
  constructor(props) {
    super(props);
    this.state = {
      modalVisible: false,
      matId: '',
      matName: '',
      mats: [],
      playtime: '',
    };
  }
  componentDidMount() {
    this.props.dispatch({
      type: 'cutinlib/fetch',
      payload: {}, // 仅获取已经审核通过的
    });
    this.props.dispatch({
      type: 'cutinlib/fetchMatTime',
      payload: {},
    });
    this.props.dispatch({
      type: 'dev/fetchCityCodes',
    });
  }

  setVisible = value => {
    this.setState({
      modalVisible: value,
    });
  };

  setMatId = value => {
    this.setState({
      mats: [...this.state.mats, ...value],
    });
  };

  renderMats = () => {
    const { mats } = this.state;
    const gridStyle = {
      width: '25%',
      textAlign: 'center',
      height: 300,
    };
    return (
      <Card>
        {mats.map(item => (
          <Card.Grid style={gridStyle}>
            <Button type="primary" shape="circle" icon="search" />
            <img src={item.imeUrl} style={{ width: '100%' }}></img>

            <p>素材实例名称：{item.imeName}</p>
            <p>插播素材类型：{item.matType}</p>
            <p>插播时长：{item.icPlayTimeLen}秒</p>
          </Card.Grid>
        ))}
      </Card>
    );
  };

  deleteMat = item => {
    this.setState(({ mats }) => {
      const index = mats.indexOf(item);
      const newFileList = mats.slice();
      newFileList.splice(index, 1);
      return {
        mats: newFileList,
      };
    });
  };
  onChange = value => {
    console.log('Selected Time: ', value);
    this.setState({ playtime: value });
  };

  renderMat = () => {
    const { mats } = this.state;
    const gridStyle = {
      width: '25%',
      textAlign: 'center',
      height: 300,
    };
    return (
      <Row gutter={16}>
        {mats.map(item => (
          <Col span={7}>
            <Card
              title={item.imeName}
              bordered={false}
              extra={
                <Button
                  shape="circle"
                  icon="close"
                  onClick={() => this.deleteMat(item)}
                  size="small"
                />
              }
            >
              <img src={item.imeUrl} style={{ width: '100%' }}></img>
              <p>插播素材类型：{item.matType}</p>
              <p>插播时长：{item.icPlayTimeLen}秒</p>
            </Card>
          </Col>
        ))}
      </Row>
    );
  };
  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        console.log('values', values);
        const { playDate, date } = values;
        const { playtime } = this.state;
        let icPlayDate = '';
        let imeIds = '';
        let icPlayStartTime = '';
        let icPlayEndTime = '';
        if (playDate === 1) {
          icPlayDate = 'everyday';
        }
        if (playDate === 2) {
          let startDate = date[0].format('YYYY-MM-DD');
          let endDate = date[1].format('YYYY-MM-DD');
          icPlayDate = startDate + ',' + endDate;
        }

        const { mats } = this.state;
        console.log('mats', mats);
        if (Array.isArray(mats) === false || mats.length < 1) {
          message.error('请选择插播素材');
          return;
        } else {
          const itemimeId = mats.map(item => item.imeId);
          imeIds = itemimeId.join(',');
        }

        let jsonCont = {
          ...values,
          imeIds,
          icPlayDate,
        };
        delete jsonCont.date;
        delete jsonCont.playDate;
        if (playtime && isArray(playtime) && playtime.length > 0) {
          icPlayStartTime = playtime[0].format('HH:mm:ss');
          icPlayEndTime = playtime[1].format('HH:mm:ss');
          jsonCont = { ...jsonCont, icPlayStartTime, icPlayEndTime };
        }
        this.props.dispatch({
          type: 'cutinlib/addcutintask',
          payload: jsonCont,
          callback: () => {
            message.success('添加素材成功');
            // const encodeName = encodeURI(progName);
            this.props.history.push(`/program/cutinlist`);
          },
        });
      }
    });
  };
  FormSelect = (name, label, options, initialValue = 0) => {
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 },
      },
    };
    const { getFieldDecorator } = this.props.form;
    return (
      <FormItem {...formItemLayout} label={label}>
        {getFieldDecorator(name, {
          rules: [{ required: true, message: `请选择${label}!` }],
          initialValue,
        })(
          <Select placeholder={`请选择${label}!`} onChange={this.handleSelectChange}>
            {options.map((option, index) => (
              <Option value={index} key={index}>
                {option}
              </Option>
            ))}
          </Select>
        )}
      </FormItem>
    );
  };
  render() {
    const {
      submitting,
      cutinlib: { matTimeCodes },
      dev: { cityCodes },
    } = this.props;
    //const { getFieldDecorator } = this.props.form;
    const { getFieldDecorator, getFieldValue } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 },
      },
    };
    const formItemLayoutWithOutLabel = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 20, offset: 4 },
      },
    };
    const submitFormLayout = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 10, offset: 7 },
      },
    };

    return (
      <PageHeaderLayout title="添加插播任务">
        <Card bordered={false}>
          <Form onSubmit={this.handleSubmit} style={{ marginTop: 8 }}>
            <FormItem {...formItemLayout} label="节目名称">
              {getFieldDecorator('progName', {
                rules: [
                  {
                    required: true,
                    message: '请输入节目名称',
                  },
                ],
              })(<Input style={{ width: '50%' }} placeholder="请输入节目名称" />)}
            </FormItem>
            <FormItem {...formItemLayout} label="城市">
              {getFieldDecorator('cityId', { rules: [{ required: true, message: '请选择城市' }] })(
                <Select allowClear="true" placeholder="城市">
                  {cityCodes.map((item, index) => (
                    <Option value={item.code} key={item.code}>
                      {item.name}
                    </Option>
                  ))}
                </Select>
              )}
            </FormItem>

            <FormItem {...formItemLayout} label="插播日期">
              {getFieldDecorator('playDate', {
                rules: [
                  {
                    required: true,
                    message: '插播日期',
                  },
                ],
              })(
                <Radio.Group>
                  <Radio value={0}>即时插播</Radio>
                  <Radio value={1}>每天插播</Radio>
                  <Radio value={2}>自定义日期</Radio>
                </Radio.Group>
              )}
            </FormItem>
            {getFieldValue('playDate') === 2 ? (
              <FormItem {...formItemLayout} label="起止日期">
                {getFieldDecorator('date', {
                  rules: [
                    {
                      required: false,
                      message: '请选择起止日期',
                    },
                  ],
                })(
                  <RangePicker
                    style={{ width: '80%' }}
                    mode={['date', 'date']}
                    format="YYYY-MM-DD"
                    placeholder={['开始日期', '结束日期']}
                  />
                )}
              </FormItem>
            ) : null}

            <FormItem {...formItemLayout} label="插播时间">
              <RangePicker
                placeholder={['开始时间', '结束时间']}
                showTime={{ format: 'HH:mm:ss' }}
                format="HH:mm:ss"
                mode={['time', 'time']}
                dropdownClassName={Styles.clean}
                onChange={this.onChange}
              />
            </FormItem>

            <FormItem {...formItemLayout} label="插播频次">
              {getFieldDecorator('icPlayTime', {
                rules: [{ required: false, message: '请选择插播频次...' }],
              })(
                <Select allowClear="true" placeholder="请选择" style={{ width: '100%' }}>
                  {matTimeCodes.map(item => (
                    <Option value={item.code} key={item.code}>
                      {item.name}
                    </Option>
                  ))}
                </Select>
              )}
            </FormItem>

            <Row>
              <Col span={12}>
                <FormItem labelCol={{ span: 14 }} wrapperCol={{ span: 8 }} label="插播范围">
                  {getFieldDecorator('icScope', {
                    rules: [{ required: true, message: '选择插播范围!' }],
                    initialValue: 1,
                  })(
                    <Select placeholder="选择插播范围">
                      <Option value={0}>绑定设备</Option>
                      <Option value={1}>所有设备</Option>
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col span={12}>
                <FormItem labelCol={{ span: 4 }} wrapperCol={{ span: 8 }} label="插播模式">
                  {getFieldDecorator('icMod', {
                    rules: [{ required: true, message: '选择插播模式!' }],
                    initialValue: 1,
                  })(
                    <Select placeholder="选择插播模式">
                      <Option value={0}>批量发布</Option>
                      <Option value={1}>智能发布</Option>
                    </Select>
                  )}
                </FormItem>
              </Col>
            </Row>
            <FormItem {...formItemLayout} style={{ marginBottom: 0 }} label="选择素材">
              <Row>
                <Button
                  type="primary"
                  onClick={() => {
                    this.setVisible(true);
                  }}
                >
                  点击添加素材
                </Button>
              </Row>
              <Row>{this.state.mats.length > 0 ? this.renderMat() : ''}</Row>
            </FormItem>

            <FormItem {...submitFormLayout} style={{ marginTop: 32 }}>
              <Button type="primary" htmlType="submit" loading={submitting}>
                提交
              </Button>
            </FormItem>
          </Form>
        </Card>
        <SelectCutIn
          modalVisible={this.state.modalVisible}
          dispatch={this.props.dispatch}
          cutinlib={this.props.cutinlib}
          handleModalVisible={this.setVisible}
          setMatId={this.setMatId}
          mats={this.state.mats}
        />
      </PageHeaderLayout>
    );
  }
}
